package com.whxd.smarthome.core.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.whxd.framework.security.SecurityUtils;
import com.whxd.framework.utils.StringUtil;
import com.whxd.smarthome.api.rest.dto.GetDevicesResponseDto;
import com.whxd.smarthome.core.entity.DhDevice;
import com.whxd.smarthome.core.repository.DhDeviceDao;

@Service
public class DhDeviceServiceImpl implements DhDeviceService {
	@Autowired
	private DhDeviceDao dhDeviceDao;
	@Override
	public void saveDevice(DhDevice device) {
		dhDeviceDao.save(device);
	}
	@Override
	public List<GetDevicesResponseDto> flushAndFilterDevice(
			List<GetDevicesResponseDto> devicesResponseDtos) {
		List<DhDevice> dhDevices = new ArrayList<>();//要朝数据库里更新的
		List<GetDevicesResponseDto> filterDevices = new ArrayList<>();//过滤后返回给当前登录用户的
		String currUsername = SecurityUtils.getCurrentSecurityUser().getUsername();
		if (devicesResponseDtos != null) {
			DhDevice tempDbDhDevice = null;
			for (GetDevicesResponseDto dto : devicesResponseDtos) {
				tempDbDhDevice = new DhDevice(); 
				tempDbDhDevice = dhDeviceDao.findByDeviceId(dto.getDeviceId());
				if (tempDbDhDevice != null && !"Y".equals(tempDbDhDevice.getIsLock())) {//数据库里有此设备的信息，并且不锁定时才更新此设备
					tempDbDhDevice.setDeviceModel(dto.getDeviceModel());
					tempDbDhDevice.setDeviceNameDh(dto.getName());
					tempDbDhDevice.setOnline(dto.isOnline());
					dhDevices.add(tempDbDhDevice);//要朝数据库里更新的
					if (currUsername != null && currUsername.equals(tempDbDhDevice.getOwnerUsername())) {//TODO 到时在这里查询被分享的设备
						filterDevices.add(dto);
					}//过滤后返回给当前登录用户的
				}else if(tempDbDhDevice == null) {//无此设备的信息则此设备不正常，设为LOCK
					tempDbDhDevice = new DhDevice();
					tempDbDhDevice.setCreateDt(StringUtil.getCuttentTime("yyyy-MM-dd HH:mm:ss"));
					tempDbDhDevice.setDeviceId(dto.getDeviceId());
					tempDbDhDevice.setIsLock("Y");
					tempDbDhDevice.setDeviceType("shexiangtou");
					tempDbDhDevice.setDeviceModel(dto.getDeviceModel());
					tempDbDhDevice.setOnline(dto.isOnline());
					dhDevices.add(tempDbDhDevice);//要朝数据库里更新的
				}
			}
		}
		dhDeviceDao.save(dhDevices);
		return filterDevices;
	}
	@Override
	public void deleteDevice(String deviceId) {
		dhDeviceDao.delete(dhDeviceDao.findByDeviceId(deviceId));
	}

}
